
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
<#assign base=request.contextPath  />
    <meta name="renderer" content="webkit">
    <meta name="keywords" content="滚动条, scrollbar, 页面底部, 聊天窗口, " />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="${base}/js/layui/css/layui.css"  media="all">
    <style type="text/css">
        #desc2s{
            border: none;
            outline:none;
            width: 540px;
            height: 250px;
            max-height: 250px;

            resize:none;
            text-indent:2em;
        }
    </style>
</head>
<body>
<textarea  readonly="readonly" placeholder="暂无聊天记录" id="desc2s" autofocus></textarea>
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;"></fieldset>
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;"></fieldset>
<script type="text/javascript" src="${base}/js/zhang.js"></script>

<script src="${base}/js/jquery-1.9.1.min.js"></script>
<textarea placeholder="请输入内容" name="desc2" id="sendText"
          style="  border: none;
            outline:none;
            width: 540px;
            height: 70px;
            max-height: 250px;
            overflow:hidden;
            text-indent:2em;
            resize:none; ">
</textarea>
<div style="margin-top: 10px;margin-left: 320px;">
    <button onclick="send()" class="layui-btn layui-btn-normal" style="width: 100px;float: right;margin: 10px">发送</button>
</div>

</body>

<script>

    findMSG();
    scTop();
    var websocket = null;
    //用户账户
    var userno="${user.username}";

    //判断当前浏览器是否支持WebSocket
    if ('WebSocket' in window) {
        var url= window.location.host+"${base}";
        websocket = new WebSocket("ws://"+url+"/websocket/"+userno);
    }
    else {
        alert('当前浏览器不兼容WebSocket,无法启动聊天功能')
    }


    //连接发生错误的回调方法
    websocket.onerror = function () {
       // setMessageInnerHTML("WebSocket连接发生错误");
        alert("WebSocket连接发生错误");
    };

    //连接成功建立的回调方法
    websocket.onopen = function () {
        setMessageInnerHTML("WebSocket连接成功");
    }


    //接收到消息的回调方法
    websocket.onmessage = function (event) {
        $("#desc2s").append(event.data);
       // setMessageInnerHTML(event.data);
        scTop();
    }


    //连接关闭的回调方法
    websocket.onclose = function () {
        setMessageInnerHTML("WebSocket连接关闭");
    }

    //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
    window.onbeforeunload = function () {
        closeWebSocket();
    }






    //将消息显示在网页上（当前弃用）
    function setMessageInnerHTML(sendMessage) {
        document.getElementById('message').innerHTML += sendMessage + '<br/>';
    }

    //关闭WebSocket连接
    function closeWebSocket() {
        websocket.close();
    }




    //发送消息
    function send() {

        var message = document.getElementById('sendText').value;//要发送的消息内容
        var now=getNowFormatDate();//获取当前时间

       var text= (now+"   发送人："+userno+'\n'+"           "+message) + '\n';
      $("#desc2s").append(text);

        /*document.getElementById('message').style.color="red";*/
        var ToSendUserno=userno; //接收人编号  点对点发送时候用
      //  message=message+"|"+ToSendUserno//将要发送的信息和内容拼起来，以便于服务端知道消息要发给谁
        //socket发送消息
        websocket.send(message);
        //保存聊天记录
        saveMsg(message);
        //滚动条最底
        scTop();
    }
    //获取当前时间
    function getNowFormatDate() {
        var date = new Date();
        var seperator1 = "-";
        var seperator2 = ":";
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
                + " " + date.getHours() + seperator2 + date.getMinutes()
                + seperator2 + date.getSeconds();
        return currentdate;
    }
    //漫游消息
  function saveMsg(msgText){
      $.ajax({
          type : "POST", //提交方式
          url : "${base}/messge/insertMSG",//路径
          data :{msg:msgText},
          success : function(data) {//返回数据根据结果进行相应的处理
              var datajson=JSON.parse(data);
              //判断是否保存聊天记录成功
              if (datajson.flag=="1"){
                  $("#sendText").val("");
              }else{
                  alert("服务器网络有波动，可能不会保存该条漫游聊天记录")

              }
          }
      });
  }

//聊天记录
    function findMSG(){
        $.ajax({
            type : "POST", //提交方式
            url : "${base}/messge/findMSG",//路径
            async:false,
            success : function(data) {//返回数据根据结果进行相应的处理
              for (var i=0;i<data.length;i++){
                  var text= (changeDateFormat(data[i].createTime)+"   发送人："+data[i].username+"    角色："+data[i].roleName+'\n'+"           "+data[i].msg) + '\n';
                  $("#desc2s").append(text);
              }

            }
        });
    }
    //滚动条
    function scTop(){
        var div = document.getElementById('desc2s');
        div.scrollTop = div.scrollHeight;
    }
</script>
</html>